<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\User;
use app\common\tool\Result;
use think\exception\ValidateException;
use app\common\model\Practice as PracticeModel;
use app\common\model\PracticeBank;
use app\common\model\PracticeAnswer;
use app\common\model\Exam;
use app\common\model\Cate;

class Practice extends Base
{

    /**
     * 生成练习试卷
     */
    public function createExam()
    {
        try {
            $param = $this->request->post();
            return Result::fastReturn(PracticeModel::createExam($param, $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取试卷内容
     */
    public function getExam()
    {
        try {
            $user = $this->user;
            $cate = Cate::where('id', $user->cate)->find();
            if (empty($cate)) {
                return ['code' => -1, 'msg' => '暂无课程类型'];
            }
            $info = PracticeModel::where(['uid' => $user->id])->order('create_time desc')->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '暂无练习试卷'];
            }
            $data['title'] = $info['title'];
            $data['end_time'] = $info->status == 2 ? '' : $info->end_time;
            $data['status'] = $info->status;
            $data['count'] = $info['radio_num'] + $info['check_num'];
            $data['score'] = $info->status == 1 ? '' : $info->score;
            $data['answer_count'] = PracticeAnswer::where(['practice_id' => $info['id'],'uid' => $user->id])->count();
            $radio = PracticeBank::where(['practice_id' => $info['id'], 'uid' => $user->id, 'types' => 1])->order('id asc')->field('exam_id as id')->select();
            foreach ($radio as $k => $value) {
                $value['bh'] = $k + 1;
                if ($info->status == 1) {
                    $value['status'] = 3; //未答题
                } else {
                    $PracticeAnswer = PracticeAnswer::where(['practice_id' => $info['id'],'exam_id'=>$value['id'],'uid' => $user->id])->find();
                    if (empty($PracticeAnswer)) {
                        $value['status'] = 3; //未答题
                    } else {
                        $value['status'] = $PracticeAnswer->types == 1 ? 1 : 2; //1：正确，2：错误
                    }
                }
                $radio[$k] = $value;
            }
            $data['radio'] = [
                'title' => '单选题（' . ($info['radio_num'] * $info['radio_score']) . '分）',
                'count' => $info['radio_num'],
                'list' => $radio,
            ];
            $check = PracticeBank::where(['practice_id' => $info['id'], 'uid' => $user->id, 'types' => 2])->order('id asc')->field('exam_id as id')->select();
            foreach ($check as $k => $value) {
                $value['bh'] = $k + 1;
                if ($info->status == 1) {
                    $value['status'] = 3; //未答题
                } else {
                    $PracticeAnswer = PracticeAnswer::where(['practice_id' => $info['id'], 'exam_id'=>$value['id'],'uid' => $user->id])->find();
                    if (empty($PracticeAnswer)) {
                        $value['status'] = 3; //未答题
                    } else {
                        $value['status'] = $PracticeAnswer->types == 1 ? 1 : 2; //1：正确，2：错误
                    }
                }
                $check[$k] = $value;
            }
            $data['check'] = [
                'title' => '多选题（' . ($info['check_num'] * $info['check_score']) . '分）',
                'count' => $info['check_num'],
                'list' => $check,
            ];
            $topic_id = !empty($radio)?$radio[0]['id']:(!empty($check)?$check[0]['id']:'');
            $topic = PracticeModel::getTopic($topic_id);
            
            if ($info->status == 2) {
                $PracticeAnswer = PracticeAnswer::where(['practice_id' => $info['id'], 'exam_id'=>$topic_id,'uid' => $user->id])->find();
                // print_r($PracticeAnswer);die;
                $Exam=Exam::where('id',$topic_id)->find();
                $topic['my_answer'] =  !empty($PracticeAnswer)?$PracticeAnswer['answer']:'';
                $topic['answer'] =  $Exam['answer'];
                $topic['parse'] =  $Exam['parse'];
            }
            $data['topic'] = $topic;
            return Result::success('获取成功！', $data);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取题目
     */
    public  function getTopic($id)
    {
        try {
            $user = $this->user;
            $cate = Cate::where('id', $user->cate)->find();
            if (empty($cate)) {
                return ['code' => -1, 'msg' => '暂无课程类型'];
            }
            $info = PracticeModel::where(['uid' => $user->id])->order('create_time desc')->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '暂无练习试卷'];
            }
            $data = PracticeModel::getTopic($id);
            if ($info->status == 2) {
                $PracticeAnswer = PracticeAnswer::where(['practice_id' => $info['id'], 'exam_id'=>$id,'uid' => $user->id])->find();
                $Exam=Exam::where('id',$id)->find();
                $data['my_answer'] =  !empty($PracticeAnswer)?$PracticeAnswer['answer']:'';
                $data['answer'] =  $Exam['answer'];
                $data['parse'] =  $Exam['parse'];
            }
            return Result::success('获取成功！', $data);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 判断对错
     */
    public  function judge()
    {
        try {
            $param = $this->request->get();
            $Exam = Exam::where(['id'=>$param['id']])->find();
            if(empty($Exam)){
                return Result::fail('题目不存在！');
            }
            if($Exam['answer'] == $param['answer']){
                $status = 1;
            }else{
                $status = 2;
            }
            $data['my_answer'] =  $param['answer'];
            $data['answer'] =  $Exam['answer'];
            $data['parse'] =  $Exam['parse'];
            $data['status'] =  $status;
            return Result::success('获取成功！',$data);
        }catch (\Exception $e){
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 提交试卷
     */
    public  function submit()
    {
        try {
            $param = $this->request->post();
            return Result::fastReturn(PracticeAnswer::submit($param,$this->user));
        }catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
